package me.zk.practice1.s;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * @author zhangkai
 * @date 2023/7/15 16:18
 */
public class LS_Offer_64 {
    int res,k;

    public int kthLargest(TreeNode root, int k) {
        this.k = k;
        dfs(root);
        return res;
    }
    public void dfs(TreeNode root) {
        if (root == null){
            return;
        }

        dfs(root.right);
        if (k==0){
            return;
        }
        if (--k == 0) {
            res = root.val;
            return;
        }
        dfs(root.left);
    }




    public int kthLargest2(TreeNode root, int k) {
        PriorityQueue<Integer> queue = new PriorityQueue<>(Comparator.reverseOrder());
        put(root,queue);
        for (int i = 0; i < k-1; i++) {
            queue.poll();
        }
        return queue.poll();
    }

    public void put(TreeNode node, Queue<Integer> queue) {
        if (node == null) {
            return;
        }
        queue.add(node.val);
        put(node.left,queue);
        put(node.right,queue);
    }
}
